package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.behavior.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Long articleId = dto.getArticleId();
        Integer userId = user.getId();

        String o = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + articleId, userId.toString());
        if (o != null) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(o, ReadBehaviorDto.class);
            Short totalCount = readBehaviorDto.getCount();
            Short currentCount = dto.getCount();
            Short newCount = (short) (totalCount + currentCount);
            dto.setCount(newCount);
        }

        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + articleId, userId.toString(), JSON.toJSONString(dto));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}